package com.example.f1.conf;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;

@Configuration
public class RedisC {
    public static ObjectMapper objectMapper;

    static {
        ObjectMapper b = new ObjectMapper();
        //默认转long类型
        //fixme 注意这个会被下面的配置activateDefaultTyping覆盖,导致不生效 https://segmentfault.com/q/1010000043690114
        b.enable(DeserializationFeature.USE_LONG_FOR_INTS);

        //https://zhuanlan.zhihu.com/p/148753594
//        b.activateDefaultTyping(BasicPolymorphicTypeValidator.builder().allowIfBaseType(Object.class).build()
//                , ObjectMapper.DefaultTyping.NON_FINAL
//                , JsonTypeInfo.As.WRAPPER_ARRAY);
        objectMapper = b;


    }

    @Bean("redisTemplate")
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        //GenericJackson2JsonRedisSerializer
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(objectMapper, Object.class);
        template.setKeySerializer(RedisSerializer.string());
//        template.setValueSerializer(serializer);
        template.setValueSerializer(RedisSerializer.string());
        template.setHashKeySerializer(RedisSerializer.string());
        template.setHashValueSerializer(RedisSerializer.string());
        return template;
    }
}
